/**
 * 商品详情页
 */
// pages/index/merchDetail/merchDetail.js
import CommonPage from "../../common/CommonPage.js"
const app =getApp()
const api = require('../../api/http.js')
const config = require('../../../config.js')
class MerchDetailPage extends CommonPage{

  /**
   * 页面的初始数据
   */
  constructor(...args) {
    super(...args)
    super.$init({
      id: null,
      name: null,
      img: null,
      amount: 0,
      price: 0, //商品价格
      coin: 0,  //我的叨币余额
      height: '128rpx',
      showImage: 'true',
      titleName: "礼品兑换",
      backImagePath: getApp().globalData.backImagePath,
      imageHeight: '600rpx',
      eList: [],
    })
  }
  initData = function(query, resolve, reject) {
    // var query = JSON.parse(query)
    var that = this
    var param = {
      merchId: Number(query.id)
    }
    api.post(config.exchangeListOfMerchUrl, param).then(res => {
      console.debug("商品兑换列表：", res)
      for (var i in res) {
        //TODO null filter
        res[i].userName = res[i].userName[0]
        var str = that.dateParse(res[i].createTime)
        res[i].createTime = str
      }
      that.data.eList = res
      that.data.height = app.globalData.titleHeight
      that.data = Object.assign(that.data, query) //不能深拷贝嵌套的对象
      // that.data.coin = Number(that.data.coin)
      // that.data.price = Number(that.data.price)
      that.$setData(that.data)
    }).catch(e => {
      console.error(e)
    })

    
  }
  $onNavigator(query) {
    console.debug("预加载-商品详情；参数：", query)
    this.$put("merchdetail-data", this.initData.bind(this), query)
  }
  /**
   * 返回按钮
   */
  back = function(params) {
    wx.navigateBack();
  }
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad = function(args) {
    console.debug("商品详情：", args)
    var dat = this.$take("merchdetail-data")
    if (dat) return
    this.initData(args)
  }
  /**
   * 生命周期函数--监听页面显示
   */
  onShow = function() {
    var that = this
  }

  exchangeMerchandise = function (e) {
    console.debug("兑换事件", e)
    var that = this
    if (app.globalData.hasUserInfo) {
      var data = app.globalData
      var dat = e.currentTarget.dataset
      if (dat.amount < 1) {
        wx.showToast({
          title: '您来晚了，商品都被领完啦！',
          icon: 'none'
        })
      } else {
        //是否兑换过没寄送的
        var param = {
          openId: data.userInfo.openId,
          merchId: dat.id
        }
        api.post(config.isExchangedUrl, param).then(res => {
          console.debug("兑换检查\n", res)
          if (res.exchangeId != 0 && res.stat == 0) {
            wx.showToast({
              title: '已经兑换过啦！先领取礼包再来吧^_^',
              icon: 'none',
              image: '',
              duration: 1500,
              mask: true,
              success: function (res) { },
              fail: function (res) { },
              complete: function (res) { },
            })
          } else {
            var param = {
              openId: data.userInfo.openId,
              tokenId: data.tokenId,
              userId: data.userId,
              merchId: e.currentTarget.dataset.id,
              step: data.step,
              ldt: Math.floor(data.ldt)
            }
            console.log(param)
            api.post(config.exchangeMerchandiseUrl, param).then(res => {
              console.log("兑换返回结果", res)
              if (res == "OK" || res.code == "OK") {
                wx.showToast({
                  title: '兑换成功!^_^',
                })
              }
            }).catch(e => {
              wx.showToast({
                title: '兑换失败！>_<',
              })
              console.log(e.errMsg)
            })
          }
          }
        )
      }
    } else {
      wx.showToast({
        title: "为保证程序功能可用，请先授权登录^_^",
        icon: 'none',
        duration: 1000,
      })
    }
  }
  

  dateParse = function(time) {
    var time = time.split('-')
    var date = new Date()
    var str = ""
    // var m = date.getMonth() - Number(time[0]) + 1
    var d = date.getDate() - Number(time[1])
    var h = date.getHours() - Number(time[2])
    var mi = date.getMinutes() - Number(time[3])
    // console.log(time, m, d, h, mi)
    if (d < 0) {
      d += 30
      str = d + "天前"
    } else if(d == 0) {
      if (h < 0) {
        h += 24
        str = h + "小时前"
      } else if(h == 0) {
        if (mi < 0) {
          mi += 60
          str = mi + "分钟前"
        } else if(mi == 0) {
          str = "刚刚"
        } else {
          str = mi + "分钟前"
        }
      } else {
        str = h + "小时前"
      }
    } else {
      str = d + "天前"
    }
    // console.log(time, m, d, h, mi)
    return str
  }
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage = function(res) {
    console.log("商品详情页分享信息：", res)
    var user = {}
    if (!app.globalData.hasUserInfo) {
      user = wx.getStorageSync("userInfo")
      if (!user.openId) {
        console.error("用户信息未同步！")
        return {
          title: "找回童年的回忆^_^!!!",
          desc: "你的好友邀你一起玩叨币道赢奖品！TAT",
          path: "/pages/index/auth/auth",
        }
      }
      app.globalData.userInfo = user
      app.globalData.hasUserInfo = true
    } else {
      user = app.globalData.userInfo
    }
    
    if (res.from === "menu") {
      return {
        title: "找回童年的回忆^_^!!!",
        desc: user.nickName + "邀您一起玩叨币道赢奖品！TAT",
        path: "/pages/index/auth/auth",
      }
    }
    if (res.from === 'button') {
      var user = app.globalData.userInfo
      var step = app.globalData.step
      return {
        title: user.nickName + "发起了叨币换礼物，快来帮帮TAT！",
        desc: "使用叨币就可换取童年回忆！",
        imageUrl: "http://cmechat.xyz/daobidao/uploads/images/logo.png",
        path: "/pages/index/auth/auth?pageId=1&name=" + user.nickName + "&step=" +step+"&openId="+user.openId,
        success: function (re) {
          //TODO: shareTicket
        },
      }
    } 
  }
}
// Page(new MerchDetailPage())
Page(new MerchDetailPage({ clazzName: "MerchDetailPage" }))

